package studysystem.demo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import studysystem.demo.tool.Mess;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import studysystem.demo.bean.*;

@Controller
public class LoginController {
 //测试OK
    @CrossOrigin
    @RequestMapping("/loginUser")
    @ResponseBody
    public Mess loginUser(String username, String password, HttpServletRequest httpServletRequest) {
        System.out.println("sessionId:" + httpServletRequest.getSession().getId());
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        System.out.println("用户名:" + username + " 密码:" + password);
        String b;
        String c = "";
        try {
            subject.login(usernamePasswordToken);   //完成登录;
            subject.getSession().setTimeout(-1000);
            if(username.length()==11) {
//                Learner user = (Learner) subject.getPrincipal();
//                httpServletRequest.getSession().setAttribute("user", user);
                b = "登录成功!";
                c = "学习者";
            }else if(username.length()==10){
//                Manager user = (Manager) subject.getPrincipal();
//                httpServletRequest.getSession().setAttribute("user", user);
                b = "登录成功!";
                c = "管理员";
            }else if(username.length()==2){
//                Sys_Manager user = (Sys_Manager) subject.getPrincipal();
//                httpServletRequest.getSession().setAttribute("user", user);
                b = "登录成功!";
                c = "系统管理员";
            }else {
                b = "";
            }
            System.out.println(b+"  "+c);
            return Mess.login(b, c);
        } catch (Exception e) {
            b = "用户名密码错误!";
            return Mess.login(b,c);//返回登录页面
        }
    }

    //退出
    @RequestMapping(value = "/logoutUser",method = RequestMethod.POST)
    public void userLogout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }

}
